<template>
  <div class="basetable" element-loading-text="拼命加载中">
    <!-- v-loading 设置加载 -->
    <div class="selectMenu">
      <el-button size="small" class="add" type="primary" @click="add">新增</el-button>
      <span class="spansearch">用户名</span>
      <el-input size="small" placeholder="用户名搜索" style="width: 350px; margin-left: 16px" @input="searchClick" clearable
        v-model="input1">
      </el-input>
    </div> 
    <el-dialog title="添加用户" :visible.sync="dialogFormVisiblea" width="600px" @close='closeDialog'>
      <!-- 新增 -->
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-input v-model="form.username" auto-complete="off" @change="changea()" class="inputa"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-input v-model="form.nickname" auto-complete="off" @change="changea()" class="inputa"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择角色" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-select v-model="value" placeholder="请选择" @change="select($event)">
            <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-input show-password v-model="form.password" auto-complete="off" @change="changea()" class="inputa"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-upload
            class="avatar-uploader"
            action="http://px.0123china.cn/api/v1.upload/up"
            :multiple="false"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="pic" :src="'http://px.0123china.cn'+pic" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- <img :src="imgsrcUrl" alt="" class="image" /> -->
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <label class="labela"
            ><input v-model="radio" type="radio" value="1" @change="getRadioVal"/>启用</label
          >
          <label>
            <input v-model="radio" type="radio" value="0" @change="getRadioVal"
            />禁用</label
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <!-- 设置触发更新的方法 -->
        <el-button type="primary" :plain="true" @click="updatea"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <div class="tableMain">
      <el-table :data="userList.slice((currentPage - 1) * pagesize, currentPage * pagesize)" style="width: 100%"
      >
        <el-table-column type="index" width="100" label="序号"
        ></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="nickname" label="姓名"></el-table-column>
        <el-table-column prop="avatar" label="头像">
          <template scope="scope">
            <img :src="scope.row.avatar" width="80" height="80"/>
          </template>
          
        </el-table-column>
        
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">禁用</span>
            <span v-else>启用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 点击编辑进入编辑页面进行编辑表格数据 -->
            <el-button size="medium" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="medium" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>    
    <el-dialog title="修改信息" :visible.sync="dialogFormVisible" width="600px" @close='closeDialogchack'>
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-input
            v-model="form.username"
            auto-complete="on"
            @change="changea()"
            style="width: 50%"
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-input
            v-model="form.nickname"
            auto-complete="on"
            @change="changea()"
            style="width: 50%"
          ></el-input>
        </el-form-item>

        <el-form-item label="头像" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-upload
            class="avatar-uploader"
            action="http://px.0123china.cn/api/v1.upload/up"
            :multiple="false"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="avatarimg" :src="avatarimg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="选择角色" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <el-select
            v-model="value"
            placeholder="请选择"
            @change="select($event)"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          style="width: 50%;margin-bottom:20px;"
        >
          <el-input
            placeholder="密码为空时默认不修改"
            v-model="passwordInput"
            type="password"
            style="margin-bottom:20px;"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="状态" :label-width="formLabelWidth" style="margin-bottom:20px;">
          <label class="labela"
            ><input
              v-model="radio"
              type="radio"
              value="1"
              @change="getRadioVal"
            />启用</label
          >
          <label
            ><input
              v-model="radio"
              type="radio"
              value="0"
              @change="getRadioVal"
            />禁用</label
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <!-- 设置触发更新的方法 -->
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 25, 50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userList.length"
    >
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      name:"",
      fileList: [],
      passwordInput:"",
      activeName: "first",
      options: [],
      options1: [],
      value: "",
      value: "",
      radio: "",
      rowid: "",
      dialogFormVisible: false,
      dialogFormVisiblea: false,
      dialogFormVisibleaa: false,
      formLabelWidth: "100px",
      form: {},// 设置form用于进行添加的时候绑定值
      currentPage3: 1,
      currentIndex: "",
      yonghuid: "",
      RoleLists: [],
      roleID: [],
      input: "",
      roledalete: [],
      addAdmin: [],
      radioVal: "",
      currentPage: 1, //初始页
      pagesize: 10, //    每页的数据
      userList: [],
      input1: "", //搜索
      imageUrl: "",
      file: "",
      fd:"",
      pic:"",
      picc:"",
      avatarimg:"",
      leta:"",
    };
  },

  created() {
    // this.roleLists();]
    this.userLists();
    this.roleLists();
  },

  methods: {
    closeDialog(){
      this.pic = '';
      this.value = '';
      this.radio='';
    },
    closeDialogchack(){
      this.passwordInput=''
    },
    beforeAvatarUpload(file) {
      //上传前的函数
      //上传前对图片类型和大小进行判断
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      this.pic = res.pic//上传图片接口
      this.avatarimg = "http://px.0123china.cn"+res.pic
      console.log("res",res);
      console.log("file",file);
      this.picc = URL.createObjectURL(file.raw);
      console.log("this.picc",this.picc);
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size;
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
    },
    //角色列表
    async roleLists() {
      let yonghu = (await this.$api.home.roleLists({})).data.data;
      this.options1 = yonghu;
      console.log("yonghu",yonghu);
    },
    select(e) {
      console.log("e",e);
      this.yonghuid = e;
    },
    handleClick(tab, event) {},

    getRadioVal(event) {
      this.radioVal = event.target.value;
      console.log("this.radioVal",this.radioVal);
    },

    changea() {
      console.log(",",this.form.username);
      console.log(",",this.form.nickname);
    },

    //管理员列表
    async userLists() {
      let a = await this.$api.home.adminLists();
      this.userList = a.data.data;
      console.log("this.userList",this.userList);
    },
    //管理员添加
    add() {
      this.form = {
        name: "",
      };
      //   设置点击按钮之后进行显示对话框
      this.dialogFormVisiblea = true;
    },
    //修改管理员列表
    async update() {
      let imga= this.pic
      console.log("pic",this.pic);
      if(imga == ""){
        imga = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
      }else{
        imga= this.pic
      }
      let b = (
        await this.$api.home.adminEdit({
          role: this.form.role,
          id: this.form.id,
          status: this.radioVal,
          username: this.form.username,
          nickname: this.form.nickname,
          password: this.passwordInput,
          avatar: imga,
        })
      ).data;
      console.log("b",b);
      if(b.code == 200){
        this.dialogFormVisible = false;
        this.dialogFormVisiblea = false;
        this.userLists()
          this.$notify({
          title: "成功",
          message: b.msg,
          type: "success",
          })
      }else{
        this.$notify.error({
            title: "错误",
            message: b.msg,
          });
      }
    },
    //添加
    updatea() {
      let imga= this.picc
      if(imga == ""){
        imga = "../../../public/img/carid.png"
      }else{
        imga= this.picc
      }
      axios.post("http://px.0123china.cn/api/v1.admin_user/add",{
          role: this.yonghuid,
          status: this.radioVal,
          username: this.form.username,
          nickname: this.form.nickname,
          password: this.form.password,
          avatar: imga,
      }).then(res=>{
        let add= res.data
        console.log("add",add);
        if(add.code == 200){
          this.userList.push(this.form);
          this.dialogFormVisiblea = false;
          this.$notify({
          title: "成功",
          message: add.msg,
          type: "success",
          })
        }else{
          this.$notify.error({
            title: "错误",
            message: add.msg,
          });
        }
      })
    },
    handleEdit(index, row) {
      console.log(row.id);
      this.value = row.id
      this.avatarimg = row.avatar
      this.radio = row.status+''
      console.log("row",row.id);
      console.log("status",row.status);
      // 将数据的index传递过来用于实现数据的回显
      this.form = this.userList[index];
      this.currentIndex = index;
      // 设置对话框的可见
      this.dialogFormVisible = true;
    },
    handleDelete(index,row){
       this.$confirm("此操作会会将管理员信息删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        axios.post("http://px.0123china.cn/api/v1.admin_user/delete",{
          id: row.id,
        }).then(res=>{
          let dele = res.data
          if (dele.code == 200) {
            this.userList.splice(index, 1);
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          }
        })          
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    cancel() {
      // 取消的时候直接设置对话框不可见即可
      this.dialogFormVisible = false;
      this.dialogFormVisiblea = false;
    },

    //搜索
    searchClick() {
      let searchText = this.input1;
      let list = [];
      if (searchText) {
        list = this.userList.filter((e) => {
          return e.username.match(searchText);
        });
        this.userList = list;
      } else {
        this.userLists();
      }
    },
  },
};
</script>

<style lang="less" scope>
.tableMain {
  margin-top: 10px;
}
.image {
  width: 200px;
  height: 200px;
}
//搜索框文字
 .spansearch{
   color: #409EFF;
   font-size: 15px;
   margin-left: 20px;
 }
.page {
  float: left;
  margin-top: 10px;
}

.inputa {
  width: 70%;
}
.labela {
  margin-right: 20px;
}
.backups {
  margin-bottom: 20px;
}
.add {
  margin-top: 15px;
}

.el-input--suffix {
  .el-input-group__append {
    border-color: #1890ff;
    .btnSearch {
      background: #1890ff;
      color: #fff;
      border-radius: 0;
    }
  }
}
/* 图片上传css */
.avatar-uploader /deep/.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>